package hate.controller;


import hate.json.ResUtil;
import hate.model.Att;
import hate.model.Pro;
import io.ebean.Ebean;
import io.ebean.EbeanServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 产品管理
 */
@Controller
@RestController
@EnableAutoConfiguration
@RequestMapping("/pro")
public class ProducController {

    @Autowired
    private EbeanServer ebeanServer;
    /**
     * 新增产品
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addPro" ,method = RequestMethod.POST)
    public ResUtil addPro(HttpServletRequest request){

        ResUtil res=new ResUtil();
        String userId =request.getParameter("userId");
        String typeId =request.getParameter("typeId");
        String productName =request.getParameter("productName");
        String productIntro =request.getParameter("productIntro");
        String sort =request.getParameter("sort");
        String productImageId =request.getParameter("productImageId");

        Pro pro=new Pro();
        pro.setTypeId(typeId);
        pro.setProductName(productName);
        pro.setProductIntro(productIntro);
        pro.setSort(sort);
        pro.setProductImageId(productImageId);
        pro.setProductImage(getFilePathById(productImageId));
        Ebean.save(pro);
        res.setCode("success");

        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/quePro" ,method = RequestMethod.POST)
    public ResUtil quePro(HttpServletRequest request){
        ResUtil res=new ResUtil();
        List<Pro> pros=ebeanServer.find(Pro.class).findList();
        res.setCode("success");
        res.setData(pros);
        return res;
    }


    /**
     * 删除产品
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delPro" ,method = RequestMethod.POST)
    public ResUtil delPro(HttpServletRequest request){
        ResUtil res=new ResUtil();
        String userId =request.getParameter("userId");
        String productId =request.getParameter("productId");
        Pro pro=ebeanServer.find(Pro.class).where().eq("productId",productId).findOne();
        ebeanServer.delete(pro);
        res.setCode("success");
        return res;
    }
    //根据文件id获取文件目录
    private String getFilePathById(String id){
       return  ebeanServer.find(Att.class,id).getPath();
    }

}
